# -*- coding: utf-8 -*-
"""
手机屏幕截图的代码: screenshot.py
"""
import os, sys, subprocess, cv2
from PIL import Image
from functools import lru_cache
from .logger import logger


def log_print(info, log: bool = False):
    if log:
        logger.info(info)
    else:
        logger.debug(info)


@lru_cache
def load_img(img_filename: str):
    stream = cv2.imread(img_filename)
    logger.debug(f"load image {img_filename} from disk.")
    return stream


#----------------------------------------------------------------------
# find target
def find_img(target, template, m_degree: float = 0.02, crop: tuple = False,
             log: bool = False):
    """
    寻找target图片在template中的位置，返回应该点击的坐标。
    """
    theight, twidth = target.shape[:2]
    if template is None:
        logger.debug('screen cap return failed of None. ')
        return None
    if crop:
        # 执行模板匹配，采用的匹配方式cv2.TM_SQDIFF_NORMED
        template_crop = template[crop[1]:crop[3], crop[0]:crop[2]]
        result = cv2.matchTemplate(target, template_crop, cv2.TM_SQDIFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
        min_loc = (min_loc[0] + crop[0], min_loc[1] + crop[1])
    else:
        result = cv2.matchTemplate(target, template, cv2.TM_SQDIFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

    # 如果匹配度小于指定值，就认为没有找到。
    if min_val > m_degree:
        log_print(f"match failed: {min_val:0.4} > {m_degree}", log)
        return None

    # 绘制矩形边框，将匹配区域标注出来
    # strmin_val = str(min_val)
    # print(strmin_val)
    # cv2.rectangle(template, min_loc, (min_loc[0] + twidth, min_loc[1] + theight), (0, 0, 225), 2)
    # cv2.imshow("MatchResult----MatchingValue="+strmin_val, template)
    # cv2.imwrite('1.png', template, [int(cv2.IMWRITE_PNG_COMPRESSION), 9])
    # cv2.waitKey()
    # cv2.destroyAllWindows()
    x = min_loc[0] + twidth // 2
    y = min_loc[1] + theight // 2
    return (x, y)


#----------------------------------------------------------------------
# not used. only for ref
#----------------------------------------------------------------------

# SCREENSHOT_WAY 是截图方法，经过 check_screenshot 后，会自动递减，不需手动修改
SCREENSHOT_WAY = 2


def pull_screenshot():
    """
    获取屏幕截图，目前有 0 1 2 3 四种方法，未来添加新的平台监测方法时，
    可根据效率及适用性由高到低排序
    """
    global SCREENSHOT_WAY
    if 1 <= SCREENSHOT_WAY <= 3:
        process = subprocess.Popen(
            'adb shell screencap -p',
            shell=True, stdout=subprocess.PIPE)
        binary_screenshot = process.stdout.read()
        if SCREENSHOT_WAY == 2:
            binary_screenshot = binary_screenshot.replace(b'\r\n', b'\n')
        elif SCREENSHOT_WAY == 1:
            binary_screenshot = binary_screenshot.replace(b'\r\r\n', b'\n')
        f = open('tmall.png', 'wb')
        f.write(binary_screenshot)
        f.close()
    elif SCREENSHOT_WAY == 0:
        os.system('adb shell screencap -p /sdcard/tmall.png')
        os.system('adb pull /sdcard/tmall.png .')


TEST_FILENAME = './test.png'

def check_screenshot():
    """
    检查获取截图的方式
    """
    global SCREENSHOT_WAY
    if os.path.isfile(TEST_FILENAME):
        try:
            os.remove(TEST_FILENAME)
        except Exception:
            logger.error("test file remove failed. ")
    if SCREENSHOT_WAY < 0:
        logger.error('not support screencap...')
        sys.exit()
    pull_screenshot()
    try:
        Image.open(TEST_FILENAME).load()
        logger.info(f'screen shot way: {SCREENSHOT_WAY}')
    except Exception:
        SCREENSHOT_WAY -= 1
        check_screenshot()
